package controller

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"image"
	"image/color"
	"image/png"
	"net/http"
	"os"
)

type BaseNet struct {
}

var BaseNetObj = new(BaseNet)

type reqPng struct {
	Lines [][]float64 `json:"lines"`
}

// outpng
func (b *BaseNet) Outpng(c *gin.Context) {
	var req reqPng
	_ = c.ShouldBind(&req)
	//fmt.Println(req.Lines)
	//req.Lines转存为json

	//119, 38
	maxLat := 36.2
	minLng := 119.5
	var resultLines [][]int
	for _, v := range req.Lines {
		var resultLine []int
		latY := (maxLat - v[0]) * 10000
		lngX := (v[1] - minLng) * 10000
		resultLine = append(resultLine, int(latY), int(lngX))
		resultLines = append(resultLines, resultLine)
	}
	fmt.Println(resultLines)
	//读取图片 ./public/yh.png;将resultLines的点画到图片上（红色）；返回图片
	f1, _ := os.Open("./public/image/yh33.png")
	defer f1.Close()
	img1, _, _ := image.Decode(f1)
	imgRgb := img1.(*image.NRGBA)
	for idx, v := range resultLines {
		imgRgb.Set(v[1], v[0], color.RGBA{R: 255, A: 255})
		if idx != 0 {
			for i := v[1] - 5; i < v[1]+5; i++ {
				for j := v[0] - 5; j < v[0]+5; j++ {
					imgRgb.Set(i, j, color.RGBA{R: 255, A: 255})
				}
			}
		}
	}
	//返回图片
	out, err := os.Create("./public/image/yhTemp.png")
	if err != nil {
		panic(err)
	}
	defer out.Close()
	png.Encode(out, imgRgb)
	//	返回文件
	c.File("./public/image/yhTemp.png")
}

type lineJsonStruct struct {
	Type     string `json:"type"`
	Features []struct {
		Type       string `json:"type"`
		Id         int    `json:"id"`
		Properties struct {
			DrawType string `json:"_draw_type"`
		} `json:"properties"`
		Geometry struct {
			Type        string      `json:"type"`
			Coordinates [][]float64 `json:"coordinates"`
		} `json:"geometry"`
	} `json:"features"`
}

func (b *BaseNet) OutJson(c *gin.Context) {
	var req reqPng
	_ = c.ShouldBind(&req)
	//"C:\\Users\\chun\\Desktop\\Go\\pure\\public\\json\\testLine.json"
	//读取json文件
	//解析json文件
	filePath := "C:\\Users\\chun\\Desktop\\Go\\pure\\public\\json\\testLine.json"

	// Read JSON file
	fileBytes, err := os.ReadFile(filePath)
	if err != nil {
		c.String(http.StatusInternalServerError, "Failed to read JSON file")
		return
	}

	// Parse JSON
	var jsonData lineJsonStruct
	err = json.Unmarshal(fileBytes, &jsonData)
	if err != nil {
		c.String(http.StatusInternalServerError, "Failed to parse JSON file")
		return
	}

	// Access the parsed data
	for _, v := range req.Lines {
		v[0], v[1] = v[1], v[0]
	}
	jsonData.Features[0].Geometry.Coordinates = req.Lines
	fmt.Println(jsonData)
	// Write JSON file
	jsonBytes, err := json.Marshal(jsonData)
	if err != nil {
		c.String(http.StatusInternalServerError, "Failed to marshal JSON")
		return
	}

	err = os.WriteFile(filePath, jsonBytes, 0644)
	if err != nil {
		c.String(http.StatusInternalServerError, "Failed to write JSON file")
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"message": "JSON file updated",
	})
}
